package com.mls.fivedistrict.server.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.dao.ReceiveRecordMapper;
import com.mls.fivedistrict.dao.RecordMapper;
import com.mls.fivedistrict.enums.RecordProductTypeEnum;
import com.mls.fivedistrict.enums.RecordStatusEnum;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.ReceiveRecord;
import com.mls.fivedistrict.pojo.ReceiveRecordExample;
import com.mls.fivedistrict.pojo.Record;
import com.mls.fivedistrict.pojo.RecordExample;
import com.mls.fivedistrict.server.ReceiveRecordService;
import com.mls.fivedistrict.server.RecordService;
import com.mls.fivedistrict.util.DateUtils;
import com.mls.fivedistrict.util.JsonUtils;
import com.mls.fivedistrict.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chenxiuxiang on 2018/4/13.
 */
@Service("receiveRecordService")
public class ReceiveRecordServiceImpl implements ReceiveRecordService {
    @Autowired
    ReceiveRecordMapper receiveRecordMapper;
    @Autowired
    RecordMapper recordMapper;

    @Autowired
    RecordService recordService;

    @Transactional
    @Override
    public int insertTransferRecord(Date date) {
        long l = date.getTime() - 3 * 24 * 60 * 60 * 1000-1;
        date = new Date(l);
        int i = receiveRecordMapper.transferInsert(date);
        //转移已完成的记录
        //2.删除转移记录
        if (i > 0) {
            int i1 = recordService.deleteTransferRecord(date);
            if (i1 <= 0) {
                throw new CustomerException("执行出错");
            }
        }
        return i;
    }

    @Override
    public PageInfo getAllRecord(PageFilter pageFilter) {
        //1.查询记录表中已被领取的记录
        RecordExample recordExample = new RecordExample();
        getRecordExample(recordExample, pageFilter);
        long recordCount = recordMapper.countByExample(recordExample);
        //大于总页去receive_record表中获取
        ReceiveRecordExample receiveRecordExample = new ReceiveRecordExample();
        getReceiveRecordExample(receiveRecordExample, pageFilter);
        long receiveCount = receiveRecordMapper.countByExample(receiveRecordExample);
        //计算当前record共多少页
        int countPage = (int) Math.ceil(recordCount * 1.0 / pageFilter.getPageSize());
        if (countPage < pageFilter.getPageNum()) {
            int reduse = (int) (recordCount % 10);
            int advanceNum = 0;
            if (reduse > 0) {
                //计算刚才借出去多少
                advanceNum = pageFilter.getPageSize() - reduse;
            }
            PageHelper.offsetPage((pageFilter.getPageNum() - countPage - 1) * pageFilter.getPageSize() + advanceNum, (pageFilter.getPageSize()));
            List<ReceiveRecord> receiveRecords = this.receiveRecordMapper.selectByExample(receiveRecordExample);
            for (ReceiveRecord receiveRecord : receiveRecords) {
                receiveRecord.setValue(receiveRecord.getValue().setScale(4, BigDecimal.ROUND_DOWN));
            }
            Page pages = new Page();
            for (ReceiveRecord r : receiveRecords) {
                pages.add(r);
            }
            pages.setTotal(receiveCount + recordCount);
            pages.setPageNum(pageFilter.getPageNum());
            double p = Math.ceil((receiveCount + recordCount) * 1.0 / pageFilter.getPageSize());
            pages.setPages((int) p);
            PageInfo pageInfo = new PageInfo(pages, 8);
            return pageInfo;
        }
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<Record> records = recordMapper.selectByExample(recordExample);
        if (records.size() < pageFilter.getPageSize()) {
            List<ReceiveRecord> allReceiveRecords = new ArrayList<>();
            for (Record record : records) {
                ReceiveRecord receiveRecord = JsonUtils.jsonToPojo(JsonUtils.objectToJson(record), ReceiveRecord.class);
                allReceiveRecords.add(receiveRecord);
            }
            //代表当前record不足 去receive_record表中获取
            int reduse = (int) (recordCount % 10);
            PageHelper.startPage(1, pageFilter.getPageSize() - reduse);
            List<ReceiveRecord> receiveRecords = this.receiveRecordMapper.selectByExample(receiveRecordExample);
            allReceiveRecords.addAll(receiveRecords);
            for (ReceiveRecord receiveRecord : allReceiveRecords) {
                receiveRecord.setValue(receiveRecord.getValue().setScale(4, BigDecimal.ROUND_DOWN));
            }
            Page pages = new Page();
            for (ReceiveRecord r : allReceiveRecords) {
                pages.add(r);
            }
            pages.setTotal(receiveCount + recordCount);
            pages.setPageNum(pageFilter.getPageNum());
            double p = Math.ceil((receiveCount + recordCount) * 1.0 / pageFilter.getPageSize());
            pages.setPages((int) p);
            PageInfo pageInfo = new PageInfo(pages, 5);
            return pageInfo;

        } else {
            for (Record record : records) {
                record.setValue(record.getValue().setScale(4, BigDecimal.ROUND_DOWN));
            }
            Page pages = new Page();
            for (Record r : records) {
                pages.add(r);
            }
            pages.setTotal(receiveCount + recordCount);
            pages.setPageNum(pageFilter.getPageNum());
            double p = Math.ceil((receiveCount + recordCount) * 1.0 / pageFilter.getPageSize());
            pages.setPages((int) p);
            PageInfo pageInfo = new PageInfo(pages, 8);
            return pageInfo;


        }


    }

    private void getReceiveRecordExample(ReceiveRecordExample receiveRecordExample, PageFilter pageFilter) {
        Date startDate = getStartDate(pageFilter);
        Date endDate = getEndDate(pageFilter);
        String source = pageFilter.getFilterMap().get("source");
        ArrayList sourceFilter = getSourceFilter(source);
        ReceiveRecordExample.Criteria receiveRecordCriteria = receiveRecordExample.createCriteria();
        receiveRecordCriteria.andIsDeleteEqualTo(false);
        receiveRecordCriteria.andStatusEqualTo(RecordStatusEnum.ALREADYRECEIVE.getValue());
        receiveRecordCriteria.andUserIdEqualTo(Long.valueOf(pageFilter.getFilterMap().get("userId")));
        if (!StringUtils.isEmpty(pageFilter.getFilterMap().get("intergralId")))
            receiveRecordCriteria.andIntergralIdEqualTo(Long.valueOf(pageFilter.getFilterMap().get("intergralId")));
        receiveRecordExample.setOrderByClause("create_date desc");
        if (startDate != null)
            receiveRecordCriteria.andCreateDateGreaterThanOrEqualTo(startDate);
        if (endDate != null)
            receiveRecordCriteria.andCreateDateLessThanOrEqualTo(endDate);
        if (!StringUtils.isEmpty(source)) {
            if (sourceFilter != null) {
                receiveRecordCriteria.andSourceNotIn(sourceFilter);
            } else {
                receiveRecordCriteria.andSourceEqualTo(source);
            }

        }
    }

    private void getRecordExample(RecordExample recordExample, PageFilter pageFilter) {
        Date startDate = getStartDate(pageFilter);
        Date endDate = getEndDate(pageFilter);
        String source = pageFilter.getFilterMap().get("source");
        ArrayList sourceFilter = getSourceFilter(source);
        RecordExample.Criteria criteria = recordExample.createCriteria();
        criteria.andIsDeleteEqualTo(false);
        criteria.andUserIdEqualTo(Long.valueOf(pageFilter.getFilterMap().get("userId")));
        criteria.andStatusEqualTo(RecordStatusEnum.ALREADYRECEIVE.getValue());
        if (!StringUtils.isEmpty(pageFilter.getFilterMap().get("intergralId")))
            criteria.andIntergralIdEqualTo(Long.valueOf(pageFilter.getFilterMap().get("intergralId")));
        if (startDate != null)
            criteria.andCreateDateGreaterThanOrEqualTo(startDate);
        if (endDate != null)
            criteria.andCreateDateLessThanOrEqualTo(endDate);
        if (!StringUtils.isEmpty(source)) {
            if (sourceFilter != null) {
                criteria.andSourceNotIn(sourceFilter);
            } else {
                criteria.andSourceEqualTo(source);
            }

        }
        recordExample.setOrderByClause("create_date desc");

    }

    /**
     * 获取记录过滤开始时间
     *
     * @param pageFilter
     */
    private Date getStartDate(PageFilter pageFilter) {
        String date = pageFilter.getFilterMap().get("startDate");
        if (StringUtils.isEmpty(date)) {
            return null;
        }
        Date startDate = null;
        if (date.equals("1")) {
            String endDate = pageFilter.getFilterMap().get("endDate");
            if (StringUtils.isEmpty(endDate)) {
                pageFilter.getFilterMap().put("endDate", "1");
            }
            //代表今天
            startDate = DateUtils.getDayBegin();
        } else if (date.equals("2")) {
            String endDate = pageFilter.getFilterMap().get("endDate");
            if (StringUtils.isEmpty(endDate)) {
                pageFilter.getFilterMap().put("endDate", "2");
            }
            //代表昨天
            startDate = DateUtils.getBeginDayOfYesterday();
        } else if (date.equals("3")) {
            String endDate = pageFilter.getFilterMap().get("endDate");
            if (StringUtils.isEmpty(endDate)) {
                pageFilter.getFilterMap().put("endDate", "3");
            }
            //代表本周
            startDate = DateUtils.getBeginDayOfWeek();
        } else if (date.equals("4")) {
            String endDate = pageFilter.getFilterMap().get("endDate");
            if (StringUtils.isEmpty(endDate)) {
                pageFilter.getFilterMap().put("endDate", "4");
            }
            //代表本周
            startDate = DateUtils.getBeginDayOfMonth();
        } else {
            startDate = TimeUtils.millis2Date(Long.valueOf(date));
        }
        return startDate;
    }

    /**
     * 获取记录过滤结束时间
     *
     * @param pageFilter
     */
    private Date getEndDate(PageFilter pageFilter) {
        String date = pageFilter.getFilterMap().get("endDate");
        if (StringUtils.isEmpty(date)) {
            return null;
        }
        Date endDate = new Date();
        if (date.equals("1")) {
            //代表今天
            endDate = DateUtils.getDayEnd();
        } else if (date.equals("2")) {
            //代表昨天
            endDate = DateUtils.getEndDayOfYesterDay();
        } else if (date.equals("3")) {
            //代表本周
            endDate = DateUtils.getEndDayOfWeek();
        } else if (date.equals("4")) {
            //代表本月
            endDate = DateUtils.getEndDayOfMonth();
        } else {
            endDate = TimeUtils.millis2Date(Long.parseLong(date));
        }
        return endDate;
    }

    private ArrayList getSourceFilter(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        ArrayList<String> sourceFilters = null;
        if (source.equals(RecordProductTypeEnum.OTHER.getValue())) {
            sourceFilters = new ArrayList<>();
            sourceFilters.add(RecordProductTypeEnum.AUTHENTICATION.getValue());
            sourceFilters.add(RecordProductTypeEnum.MINING.getValue());
            sourceFilters.add(RecordProductTypeEnum.INVITE_FRIENDS.getValue());
            sourceFilters.add(RecordProductTypeEnum.REGISTER.getValue());
            sourceFilters.add(RecordProductTypeEnum.PARADROP.getValue());
            sourceFilters.add(RecordProductTypeEnum.EXTRACT.getValue());
            sourceFilters.add(RecordProductTypeEnum.COMMUNITYLEADERSREWARD.getValue());
            sourceFilters.add(RecordProductTypeEnum.COMMODITYEXCHANGE.getValue());
            sourceFilters.add(RecordProductTypeEnum.VOTE.getValue());
            sourceFilters.add(RecordProductTypeEnum.CONTRIBUTION.getValue());
            sourceFilters.add(RecordProductTypeEnum.TRANSFER.getValue());
            sourceFilters.add(RecordProductTypeEnum.AUTHENTICATION.getValue());
            sourceFilters.add(RecordProductTypeEnum.SECOND_INVITE.getValue());
        }
        return sourceFilters;
    }
//    @Override
//    public List<ReceiveRecord> getAllRecord(PageFilter pageFilter) {
//        //1.查询记录表中已被领取的记录
//        //2.总数不够继续查转移记录表中的数据
//        PageHelper.offsetPage(pageFilter.getPageNum(), pageFilter.getPageSize());
//        List<ReceiveRecord> receiveRecords = receiveRecordMapper.selectAllRecord(pageFilter.getFilterMap());
//        for (ReceiveRecord receiveRecord : receiveRecords) {
//            receiveRecord.setValue(receiveRecord.getValue().setScale(4, BigDecimal.ROUND_DOWN));
//        }
//        return receiveRecords;
//    }


    @Override
    public void deleteBatch(List<Record> recordList) {
        receiveRecordMapper.deleteBatch(recordList);

    }

    @Override
    public List<Record> getReceiveRecordList(Map params) {
        return receiveRecordMapper.getReceiveRecordList(params);
    }
}
